import React, { useState, useEffect } from 'react';
import { Table, Space, Button, Input, Card, message } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Article } from '../types/article';
import { articleService } from '../services/articleService';
import styled from '@emotion/styled';

const { Search } = Input;

const PageHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
`;

const ArticleList: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const navigate = useNavigate();

  const loadArticles = async (pageNum: number = page) => {
    try {
      setLoading(true);
      const response = await articleService.getAllArticles(pageNum, pageSize);
      setArticles(response.content);
      setTotal(response.totalElements);
    } catch (error) {
      message.error('加载文章列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadArticles();
  }, []);

  const handleSearch = async (value: string) => {
    try {
      setLoading(true);
      const response = await articleService.searchArticles(value, 0, pageSize);
      setArticles(response.content);
      setTotal(response.totalElements);
      setPage(0);
    } catch (error) {
      message.error('搜索文章失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: Article) => (
        <a onClick={() => navigate(`/articles/${record.id}`)}>{text}</a>
      ),
    },
    {
      title: '作者',
      dataIndex: ['author', 'username'],
      key: 'author',
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      sorter: (a: Article, b: Article) => a.viewCount - b.viewCount,
    },
    {
      title: '点赞数',
      dataIndex: 'likeCount',
      key: 'likeCount',
      sorter: (a: Article, b: Article) => a.likeCount - b.likeCount,
    },
    {
      title: '发布时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: Article) => (
        <Space size="middle">
          <Button type="link" onClick={() => navigate(`/articles/${record.id}/edit`)}>
            编辑
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleDelete = async (id: number) => {
    try {
      await articleService.deleteArticle(id);
      message.success('删除文章成功');
      loadArticles();
    } catch (error) {
      message.error('删除文章失败');
    }
  };

  return (
    <Card>
      <PageHeader>
        <Search
          placeholder="搜索文章"
          allowClear
          enterButton={<SearchOutlined />}
          onSearch={handleSearch}
          style={{ width: 300 }}
        />
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => navigate('/articles/new')}
        >
          写文章
        </Button>
      </PageHeader>

      <Table
        columns={columns}
        dataSource={articles}
        rowKey="id"
        loading={loading}
        pagination={{
          total,
          pageSize,
          current: page + 1,
          onChange: (pageNum) => {
            setPage(pageNum - 1);
            loadArticles(pageNum - 1);
          },
          onShowSizeChange: (current, size) => {
            setPageSize(size);
            setPage(0);
            loadArticles(0);
          },
        }}
      />
    </Card>
  );
};

export default ArticleList; 